#include "ai_service_stub.h"
#include "ai_service_log.h"
#include "ai_service_errors.h"

using namespace OHOS::HiviewDFX;

namespace OHOS {
namespace AIS {
namespace {
    constexpr HiLogLabel LABEL = {LOG_CORE, AIS_LOG_DOMAIN, "AIServiceStub"};
}

AIServiceStub::AIServiceStub()
{
    AIS_HILOGD("Construction AIServiceStub begin.");
    // GetDeviceInfo
    baseFuncs_[INIT] = &AIServiceStub::InitStub;
    // HandleMessage
    baseFuncs_[PROCESS] = &AIServiceStub::ProcessStub;

    // SecGetDeviceInfo
    baseFuncs_[DEINIT] = &AIServiceStub::DeInitStub;
}

AIServiceStub::~AIServiceStub()
{
    AIS_HILOGD("Release AIServiceStub begin.");
    baseFuncs_.clear();
}

int32_t AIServiceStub::OnRemoteRequest(uint32_t code, MessageParcel& data, MessageParcel &reply, MessageOption &option)
{
    AIS_HILOGD("remoterequest begin, cmd : %{public}u", code);
    auto itFunc = baseFuncs_.find(code);
    if (itFunc != baseFuncs_.end())
    {
        auto memberFunc = itFunc->second;
        if (memberFunc != nullptr)
        {
            return (this->*memberFunc)(data, reply);
        }
    }
    AIS_HILOGD("remoterequest no member function default process");
    return IPCObjectStub::OnRemoteRequest(code, data, reply, option);
}

int32_t AIServiceStub::InitStub(MessageParcel &data, MessageParcel &reply)
{
    AIS_HILOGD("InitStub begin.");
    int32_t modelId = -1;  
    std::string modelPath = data.ReadString();
    auto ret = Init(modelPath, &modelId);
    if (ret != RETCODE_SUCCESS)
    {
        AIS_HILOGE("Init failed, ret: %{public}d", ret);
        reply.WriteInt32(ret);      
        reply.WriteInt32(modelId);
        return ret;
    }

    reply.WriteInt32(RETCODE_SUCCESS);      
    reply.WriteInt32(modelId);

    return RETCODE_SUCCESS;
}

int32_t AIServiceStub::ProcessStub(MessageParcel &data, MessageParcel &reply)
{
    AIS_HILOGD("ProcessStub begin.");
    int32_t modelId = data.ReadInt32();
    PicDesc picDesc = *(PicDesc *)data.ReadRawData(sizeof(PicDesc));
    std::string picData = data.ReadString();
    InferResult result {};

    auto ret = Process(modelId, picDesc, picData, result);
    if (ret != RETCODE_SUCCESS)
    {
        AIS_HILOGE("Process failed, ret: %{public}d", ret);
        reply.WriteInt32(ret);      
        return ret;
    }

    reply.WriteInt32(RETCODE_SUCCESS);
    reply.WriteRawData(&result, sizeof(InferResult));

    return RETCODE_SUCCESS;
}

int32_t AIServiceStub::DeInitStub(MessageParcel &data, MessageParcel &reply)
{
    AIS_HILOGD("DeInitStub begin.");
    auto ret = DeInit();
    if (ret != RETCODE_SUCCESS)
    {
        AIS_HILOGE("DeInit failed, ret: %{public}d", ret);
        reply.WriteInt32(ret);      
        return ret;
    }

    reply.WriteInt32(RETCODE_SUCCESS); 
    return RETCODE_SUCCESS;
}
}  // namespace AIS    
}  // namespace OHOS
